'use client';

import PlanCard from '@/components/plans/PlanCard';
import { EmptyState } from '@/components/ui/empty';
import { ErrorState } from '@/components/ui/error';
import { LoadingState } from '@/components/ui/loading';
import type { PaginatedResult } from '@/libs/pagination';
import { clientFetch } from '@/utils/request';
import { Card, Input, Pagination, Typography } from '@douyinfe/semi-ui';
import { Icon } from '@iconify/react';
import { useState } from 'react';
import useSWR from 'swr';
import { useDebounceValue } from 'usehooks-ts';

export default function HistoryPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchTerm, setSearchTerm] = useState('');

  const debouncedSearchTerm = useDebounceValue(searchTerm, 500);

  const params = new URLSearchParams({
    page: `${currentPage}`,
    pageSize: `${pageSize}`,
    ...(searchTerm && { search: debouncedSearchTerm[0] }),
  });

  const fetcher = async () => {
    const res = await clientFetch.get<PaginatedResult<any>>(
      `/api/plans?${params.toString()}`
    );

    if (res.code !== 200) {
      throw new Error(res.message || '请求失败');
    }

    return res.data;
  };

  const { data, error, isLoading } = useSWR(
    `/api/plans?${params.toString()}`,
    fetcher
  );

  const handleSearch = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1); // 重置到第一页
  };

  return (
    <div className="min-h-screen bg-gray-50 bg-gradient-to-br">
      <div className="container mx-auto px-4 py-6 sm:px-6 lg:px-8">
        {/* 页面头部 */}
        <div className="mb-8">
          <Card
            className="border-0 bg-white/80 shadow-lg backdrop-blur-sm"
            bodyStyle={{ padding: '24px' }}
          >
            <div className="flex flex-col space-y-6">
              {/* 标题区域 */}
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-3">
                  <div className="rounded-lg bg-gradient-to-r from-blue-500 to-indigo-600 p-2">
                    <Icon
                      icon="material-symbols:history"
                      className="h-6 w-6 text-white"
                    />
                  </div>
                  <div>
                    <Typography.Title
                      heading={4}
                      className="!mb-0 bg-gradient-to-r from-gray-900 to-gray-600 bg-clip-text text-transparent"
                    >
                      我的方案管理
                    </Typography.Title>
                    <Typography.Text type="secondary" className="text-sm">
                      管理和查看所有工艺方案
                    </Typography.Text>
                  </div>
                </div>

                {/* 统计信息 */}
                {data && (
                  <div className="hidden items-center space-x-4 sm:flex">
                    <div className="rounded-lg border border-blue-100 bg-gradient-to-r from-blue-50 to-indigo-50 p-3 text-center">
                      <div className="text-2xl font-bold text-blue-600">
                        {data.pagination.total}
                      </div>
                      <div className="text-xs text-gray-500">总方案数</div>
                    </div>
                  </div>
                )}
              </div>

              {/* 搜索和筛选区域 */}
              <div className="flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
                <div className="max-w-md flex-1">
                  <Input
                    prefix={
                      <Icon
                        icon="mynaui:search"
                        className="mx-2 h-4 w-4 text-gray-400"
                      />
                    }
                    placeholder="搜索工艺编码、简称或参数..."
                    className="!rounded-lg !border-gray-200 transition-colors hover:!border-blue-300 focus:!border-blue-500"
                    size="large"
                    showClear
                    value={searchTerm}
                    onChange={handleSearch}
                  />
                </div>
              </div>
            </div>
          </Card>
        </div>

        {/* 内容区域 */}
        <div className="space-y-6">
          {isLoading && !error && (
            <div className="flex justify-center py-12">
              <LoadingState />
            </div>
          )}

          {error && <ErrorState />}

          {data && data.pagination.total === 0 && (
            <div className="flex justify-center py-12">
              <EmptyState />
            </div>
          )}

          {!isLoading && !error && data && data.pagination.total > 0 && (
            <>
              {/* 方案卡片列表 */}
              <div className="grid gap-4">
                {data.data.map((record, index) => (
                  <div
                    key={record._id.toString()}
                    className="transform transition-all duration-200 hover:scale-[1.01] hover:shadow-lg"
                    style={{
                      animationDelay: `${index * 50}ms`,
                      animation: 'fadeInUp 0.5s ease-out forwards',
                    }}
                  >
                    <PlanCard record={record} />
                  </div>
                ))}
              </div>

              {/* 分页组件 */}
              <Card
                className="border-0 bg-white/60 shadow-sm backdrop-blur-sm"
                bodyStyle={{ padding: '20px' }}
              >
                <div className="flex flex-col items-center justify-between gap-4 sm:flex-row">
                  <div className="text-sm text-gray-500">
                    显示 {(currentPage - 1) * pageSize + 1} -{' '}
                    {Math.min(currentPage * pageSize, data.pagination.total)}{' '}
                    条， 共 {data.pagination.total} 条记录
                  </div>

                  <Pagination
                    total={data.pagination.total}
                    showQuickJumper
                    showSizeChanger
                    currentPage={currentPage}
                    pageSize={pageSize}
                    onPageChange={(page: number) => {
                      setCurrentPage(page);
                    }}
                    onPageSizeChange={(newPageSize) => {
                      setPageSize(newPageSize);
                      setCurrentPage(1);
                    }}
                    className="!m-0"
                  />
                </div>
              </Card>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
